package com.rzico.sbl.ui.manager

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import com.rzico.sbl.R
import com.rzico.sbl.databinding.FragmentManagerBinding
import com.rzico.sbl.model.ManagerContent
import com.rzico.sbl.model.ManagerDivider
import com.rzico.sbl.model.QRType
import com.rzico.sbl.other.ManagerDecoration
import com.rzico.sbl.ui.ScanActivity
import com.rzico.sbl.ui.member.MemberActivity
import com.rzico.sbl.ui.member.MemberAdressEditActivity
import com.rzico.sbl.ui.member.MemberOfflineActivity
import com.rzico.sbl.ui.member.MemberWarnActivity
import com.xinnuo.common.extend.*
import com.xinnuo.common_ui.base.*
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.subscribeByFinally
import com.xinnuo.common_ui.view.BadgeTextView
import com.xinnuo.slimadapter.SlimAdapter
import kotlin.text.orEmpty

class ManagerFragment : NavigationFragment() {

    private var mBinding: FragmentManagerBinding? = null

    override fun getViewModel() = get<ManagerViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) = FragmentManagerBinding
        .inflate(inflater, container, false)
        .also { mBinding = it }
        .root

    override fun initTitle() {
        initLayout()
        initListener()

        mBinding?.let {
            it.managerContent
                .swipeRefresh
                .isEnabled = false
        }

        mList.addItems(getViewModel().generateList())
        mAdapter.setDataList(mList)
    }

    private fun initLayout() {
        mBinding?.let { layout ->
            layout
                .managerContent
                .recycleList
                .apply {
                    loadGrid(
                        refresh = layout.managerContent.swipeRefresh,
                        onRefresh = { getData() },
                        init = {
                            layoutManager = GridLayoutManager(
                                getIContext(),
                                4
                            ).apply {
                                spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                                    override fun getSpanSize(position: Int): Int = when {
                                        mAdapter.getItem(position) is ManagerContent -> 1
                                        else -> 4
                                    }
                                }
                            }
                        }
                    )

                    addItemDecoration(ManagerDecoration(vertical = 15))

                    mAdapter = SlimAdapter.creator()
                        .register<ManagerDivider>(R.layout.item_manager_divider) { jector, bean, index ->

                            // 解构声明
                            val (title, show) = bean

                            jector.apply {

                                text(R.id.divder_title, title)

                                getView<View>(R.id.divder_title).isGone = index == mList.size - 1
                                getView<View>(R.id.divder_edit).isVisible = show
                                getView<View>(R.id.divder_hint1).isGone = index == 0
                                getView<View>(R.id.divder_hint2).isGone = index == mList.size - 1
                                getView<View>(R.id.divder_hint3).isVisible = index == mList.size - 1
                            }
                        }
                        .register<ManagerContent>(R.layout.item_manager_grid) { jector, bean, _ ->

                            // 解构声明
                            val (title, imageId, _, url, count) = bean

                            jector.apply {
                                text(R.id.manager_hint, title)

                                with<ImageView>(R.id.manager_image) {
                                    (imageId > 0)
                                        .conditionElse(
                                            actionTrue = { it.setImageResource(imageId) },
                                            actionFalse = { it.loadImage(url) }
                                        )
                                }

                                getView<BadgeTextView>(R.id.manager_num).setBadgeCount(count)
                                getView<View>(R.id.manager_hint).isInvisible = title.isEmpty()
                                getView<View>(R.id.manager_image).isInvisible = title.isEmpty()

                                clicked {
                                    when (title) {
                                        "会员" -> startActivityEx<MemberActivity>()
                                        "休眠会员" -> startActivityEx<MemberOfflineActivity>()
                                        "添加会员" -> startActivityEx<MemberAdressEditActivity>()
                                        "水票提醒" -> startActivityEx<MemberWarnActivity>()
                                        "员工" -> startActivityEx<MasterActivity>()
                                        "添加员工" ->
                                            startActivityEx<ScanActivity>(
                                                "mode" to QRType.MASTER,
                                                "from" to "manager"
                                            )

                                        "实时位置" -> startActivityEx<MasterMapActivity>()
                                        "员工围栏" -> startActivityEx<MasterAreaActivity>()
                                        "优惠券" -> startActivityEx<CouponActivity>()
                                        "核销券" ->
                                            startActivityEx<ScanActivity>(
                                                "mode" to QRType.COUPON,
                                                "from" to "manager"
                                            )

                                        "添加券" ->
                                            startActivityEx<CouponAddActivity>(
                                                "status" to "manager"
                                            )

                                        "普通发票" ->
                                            startActivityEx<TaxActivity>(
                                                "title" to "普通发票",
                                                "status" to "common"
                                            )

                                        "专用发票" ->
                                            startActivityEx<TaxActivity>(
                                                "title" to "专用发票",
                                                "status" to "special"
                                            )

                                        "押桶" -> startActivityEx<BarrelHandleActivity>()
                                        "退桶" -> startActivityEx<MasterBarrelActivity>()
                                        "自提点" -> startActivityEx<PickupActivity>()
                                    }
                                }
                            }
                        }
                        .attachTo(this)
                }
        }
    }

    private fun initListener() {
        getViewModel()
            .mBarrelCount
            .observe(getLifecycleOwner()) { arr ->
                val index = mList.indexOfFirst {
                    it is ManagerContent && it.title == "退桶"
                }

                (index > -1)
                    .condition {
                        (mList[index] as ManagerContent).count = arr[0] + arr[1]
                        mAdapter.notifyItemChanged(index)
                    }
            }
    }

    /**
     * 商品分类
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .productCat()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { list ->
                    mList.clear()

                    (list.count() > 0)
                        .condition {
                            mList.add(ManagerDivider("商品", true))
                            list.mapTo(mList) {
                                ManagerContent(
                                    id = it.id,
                                    title = it.name.orEmpty(),
                                    url = it.thumbnail.orEmpty()
                                )
                            }

                            (0 until (4 - list.size % 4))
                                .forEach { _ ->
                                    mList.add(ManagerContent())
                                }
                        }

                    mList.addItems(getViewModel().generateList())
                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    mBinding?.let {
                        it.managerContent
                            .swipeRefresh
                            .isRefreshing = false
                    }
                }
            )
    }

    override fun onStart() {
        super.onStart()

        getViewModel().getBarrelCount()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mBinding = null
    }

}